package com.s2paganini.text 
{
	import com.s2paganini.core.IListDisplay;
	
	import flash.text.TextField;	

	/**
	 * @author siLvio paganini | s2paganini.com
	 * @purpose List Display Field
	 * @example
	 * <p>
	 * var shoppingList : ListDisplayField = new ListDisplayField();<br>
	   shoppingList.addItem("Bread");<br>
	   shoppingList.addItem("Butter");<br>
	   shoppingList.addItem("Trash");<br><br>

	   shoppingList.deleteItem("Trash");<br>
	   shoppingList.deleteItemAt(2);<br>
	   addChild(shoppingList);
	   </p>
	 */

	public class ListDisplayField extends TextField implements IListDisplay 
	{
		private var aList : Array;

		public function ListDisplayField()
		{
			super();
			this.clear();
		}

		public function addItem(s : String) : void
		{
			this.aList.push(s);
			this.update();
		}

		private function update() : void
		{
			var listText : String = "";
			for (var i : Number = 0;i < aList.length; i++) {
				listText += aList[i] + "\r";	
			}
			
			super.text = listText;
		}

		public function deleteItemAt(n : uint) : Boolean
		{
			if((n > 0) && (n <= aList.length)) {
				aList.splice(n - 1, 1);
				this.update();
				return true;	
			} else {
				return false;	
			}
		}

		public function deleteItem(s : String) : Boolean
		{
			var result : Boolean = false;
			
			for (var i : int = 0;i < aList.length; i++) {
				if(aList[i] == s) {
					aList.splice(i, 1);
					this.update();
					result = true;
					break;
				} else {
					result = false;	
				}
			}
			return result;
		}

		public function clear() : void
		{
			aList = new Array();
			this.update();
		}

		override public function set text(s : String) : void {
			throw new Error("Cannot directly set text, use addItem() method");	
		}

		override public function set htmlText(s : String) : void {
			throw new Error("Cannot directly set htmlText property");	
		}

		override public function appendText(s : String) : void
		{
			throw new Error("Cannot append text, use addItem() method");
		}

		override public function replaceSelectedText(s : String) : void
		{
			throw new Error("Cannot replace selected text");
		}

		override public function replaceText(beginIndex : int, endIndex : int, newText : String) : void
		{
			throw new Error("Cannot replace text");
		}
	}
}
